// fileName      :  index.go
// createdAt     :  2021-10-23
// description   :

package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zl-gin/constant"
	"zl-gin/controllers"
	"zl-gin/controllers/v1/params"
	"zl-gin/my_error"
	"zl-gin/mysql/models"
	"zl-gin/services"
	"zl-gin/utils"
)

// UserLogin 用户登录
func UserLogin(c *gin.Context) {
	var data params.UserLoginParam
	if controllers.ValidateJson(c, &data) {
		user, userErr := models.GetUserInfoByName(data.UserName)
		if userErr != nil {
			c.JSON(http.StatusOK, userErr)
			return
		}

		if utils.ComparePasswords(user.Password, []byte(data.Password)) {
			token, tokenErr := services.GenerateToken(data.UserName, user.Id)
			if tokenErr != nil {
				c.JSON(http.StatusOK, constant.ResponseGetTokenFail)
				return
			}
			data := map[string]interface{}{
				"token": token,
			}
			c.JSON(http.StatusOK, constant.ResponseSuccess.SetData(data))
		} else {
			c.JSON(http.StatusOK, my_error.NewMyError(my_error.ErrCodeUserOrPwdFail))
		}
	}
}

// UserRegister 用户注册
func UserRegister(c *gin.Context) {
	var data params.UserRegisterParam
	if controllers.ValidateJson(c, &data) {
		userRegRes := models.UserRegister(data)
		if userRegRes != nil {
			c.JSON(http.StatusOK, userRegRes)
			return
		}
		c.JSON(http.StatusOK, my_error.NewMyError(my_error.ErrorCodeSuccess))
	}
}

// Userinfo 获取用户信息
func Userinfo(c *gin.Context) {
	data := map[string]interface{}{
		"userName": c.GetString(constant.AuthUserNameKey),
		"userId":   c.GetString(constant.AuthUserIdKey),
	}
	c.JSON(http.StatusOK, constant.ResponseSuccess.SetData(data))
}
